import tkinter as tk
import random
import threading
import time


class DragonBoatRaceApp:
    def __init__(self, master):
        self.master = master
        master.title("端午龙舟竞速")

        # 配置主窗口
        self.width = 800
        self.height = 600
        master.geometry(f"{self.width}x{self.height}")
        master.resizable(False, False)  # 禁止调整窗口大小
        master.configure(bg="#FFE8C5")  # 端午主题底色

        # 创建顶部标题
        title_label = tk.Label(master, text="🐉 端午节龙舟竞速大赛 🐉",
                               font=("微软雅黑", 18, "bold"), fg="#8B0000", bg="#FFE8C5")
        title_label.pack(pady=10)

        # 设置画布
        self.canvas = tk.Canvas(master, width=self.width, height=self.height - 200) # 600-180=420，这样底部有更多空间


        self.canvas.pack()

        # 添加背景装饰
        self.add_decorations()

        # 队伍信息
        self.teams = {
            "红队": {"speed": random.uniform(1.0, 1.5), "position": 0, "color": "#FF5252", "icon": "🐉"},
            "蓝队": {"speed": random.uniform(1.0, 1.5), "position": 0, "color": "#448AFF", "icon": "🚣‍♂️"},
            "黄队": {"speed": random.uniform(1.0, 1.5), "position": 0, "color": "#FFD740", "icon": "🛶"},
        }

        # 绘制起点和终点线
        self.draw_track()

        # 初始化龙舟队伍
        self.boats = {}
        self.boat_items = {}
        self.init_boats()

        # 竞猜部分
        self.guess_frame = tk.Frame(master, bg="#FFE8C5")
        self.guess_frame.pack(fill=tk.X, padx=20, pady=(5, 0))

        self.guess_label = tk.Label(self.guess_frame, text="竞猜冠军队伍：",
                                    font=("微软雅黑", 12), bg="#FFE8C5")
        self.guess_label.pack(side=tk.LEFT)

        self.selected_team = tk.StringVar()

        # 创建队伍选择按钮
        for team, data in self.teams.items():
            color = data["color"]
            btn = tk.Radiobutton(self.guess_frame, text=f"{team}{data['icon']}",
                                 variable=self.selected_team, value=team,
                                 bg=color, fg="white" if team != "黄队" else "black",
                                 selectcolor="#9C27B0",
                                 font=("微软雅黑", 11, "bold"), indicatoron=False,
                                 padx=10, pady=2, relief="ridge")
            btn.pack(side=tk.LEFT, padx=5)

        # 创建比赛控制按钮
        self.button_frame = tk.Frame(master, bg="#FFE8C5")
        self.button_frame.pack(fill=tk.X, pady=(10, 15))

        self.start_button = tk.Button(self.button_frame, text="🚩 开始比赛",
                                      command=self.start_race, bg="#4CAF50", fg="white",
                                      font=("微软雅黑", 12, "bold"), padx=20, pady=-8)
        self.start_button.pack()

        # 重置按钮
        self.reset_button = tk.Button(self.button_frame, text="🔄 重新开始",
                                      command=self.reset_race, bg="#9C27B0", fg="white",
                                      font=("微软雅黑", 10), padx=15, pady=4,
                                      state=tk.DISABLED)
        self.reset_button.pack(pady=5)

        # 状态变量
        self.running = False
        self.winner = None

    def add_decorations(self):
        """添加端午节装饰元素"""
        # 添加水波纹
        for y in range(30, self.height - 120, 40):
            self.canvas.create_line(0, y, self.width, y, fill="#BBDEFB", dash=(2, 3), width=1)

        # 添加柳树装饰
        for i in range(5):
            x = 80 + i * 150
            self.canvas.create_line(x, 50, x, 100, width=3, fill="#3E2723")
            self.canvas.create_polygon(x - 40, 80, x + 40, 80, x, 40, fill="#66BB6A", outline="#2E7D32")

        # 添加粽子图标
        self.canvas.create_text(50, self.height - 140, text="🏁", font=("Arial", 24))
        self.canvas.create_text(self.width - 50, self.height - 140, text="🥇", font=("Arial", 24))

    def draw_track(self):
        """绘制赛道和水面效果"""
        # 绘制赛道边线
        self.canvas.create_line(30, 50, 30, self.height - 170, fill="#3E2723", width=3)
        self.canvas.create_line(self.width - 30, 50, self.width - 30, self.height - 170, fill="#3E2723", width=3)

        # 绘制水面
        for y in range(150, self.height - 150, 50):
            line = self.canvas.create_line(50, y, self.width - 50, y, fill="#2196F3", dash=(10, 15))
            self.canvas.lower(line)  # 放到底层

    def init_boats(self):
        """初始化龙舟位置"""
        boat_height = 30
        boat_length = 80

        for i, (team, data) in enumerate(self.teams.items()):
            # 计算位置 (在垂直方向均匀分布)
            y_position = 100 + (self.height - 280) / len(self.teams) * i

            # 绘制船体
            boat_body = self.canvas.create_rectangle(
                30, y_position,
                30 + boat_length, y_position + boat_height,
                fill=data["color"], outline="#000000", width=2
            )

            # 绘制龙头
            head_size = 20
            boat_head = self.canvas.create_polygon(
                30, y_position + boat_height / 2,
                15, y_position + boat_height / 4,
                15, y_position + 3 * boat_height / 4,
                fill=data["color"], outline="#000000", width=1
            )

            # 绘制船尾
            tail_size = 15
            boat_tail = self.canvas.create_polygon(
                30 + boat_length, y_position + boat_height / 2,
                30 + boat_length + tail_size, y_position + boat_height / 3,
                30 + boat_length + tail_size, y_position + 2 * boat_height / 3,
                fill=data["color"], outline="#000000", width=1
            )

            # 绘制船桨
            paddles = []
            for paddle_x in [boat_length - 20, boat_length - 50]:
                paddle = self.canvas.create_line(
                    30 + paddle_x, y_position,
                    30 + paddle_x, y_position - 30,
                    fill="#5D4037", width=2
                )
                paddles.append(paddle)
                self.canvas.create_line(
                    30 + paddle_x, y_position - 30,
                    30 + paddle_x - 15, y_position - 40,
                    fill="#5D4037", width=3
                )

            # 添加队员图标
            for j in range(3):
                self.canvas.create_text(
                    40 + boat_length / 4 * j, y_position + boat_height / 2,
                    text="🏃‍♂️", font=("Arial", 12)
                )

            # 添加队伍标识
            team_label = self.canvas.create_text(
                30 + boat_length / 2, y_position - 15,
                text=f"{team}{data['icon']}",
                font=("微软雅黑", 10, "bold")
            )

            # 保存所有船部件
            self.boats[team] = [boat_body, boat_head, boat_tail, *paddles, team_label]

            # 保存初始位置信息以便重置
            self.boat_items[team] = self.canvas.bbox(boat_body)

    def start_race(self):
        """开始比赛"""
        if not self.running:
            self.running = True
            self.start_button.config(state=tk.DISABLED)

            # 禁用竞猜按钮
            for widget in self.guess_frame.winfo_children():
                if isinstance(widget, tk.Radiobutton):
                    widget.config(state=tk.DISABLED)

            # 创建动画线程
            threading.Thread(target=self.run_race).start()

    def run_race(self):
        """运行动画效果"""
        finish = False

        while not finish and self.running:
            for team, data in self.teams.items():
                # 更新位置
                data["position"] += data["speed"]

                # 检查是否到达终点
                if data["position"] >= self.width - 120:  # 终点线位置调整
                    finish = True
                    self.winner = team
                    break

                # 移动船的所有部件
                for part in self.boats[team]:
                    self.canvas.move(part, data["speed"], 0)

            # 更新画面
            self.master.update()
            time.sleep(0.05)  # 控制动画速度

        if finish:
            # 显示比赛结果
            self.show_results()

    def show_results(self):
        """显示比赛结果"""
        # 添加奖杯图标
        win_y = (self.canvas.bbox(self.boats[self.winner][0])[1] +
                 self.canvas.bbox(self.boats[self.winner][0])[3]) // 2
        self.canvas.create_text(self.width - 20, win_y - 15,
                                text="🏆", font=("Arial", 36))

        # 显示冠军队伍
        result_text = f"🏁 {self.winner} 获得冠军！"
        self.canvas.create_text(
            self.width / 2, self.height / 2 - 60,
            text=result_text, fill="#C51162",
            font=("微软雅黑", 24, "bold")
        )

        # 显示竞猜结果
        guess_text = ""
        if not self.selected_team.get():
            guess_text = "你未参与竞猜，下次记得参与哦！"
        elif self.selected_team.get() == self.winner:
            guess_text = "🎉 恭喜！你猜中了冠军队伍！🎉"
        else:
            guess_text = f"很遗憾，你猜的{self.selected_team.get()}未能夺冠"

        self.canvas.create_text(
            self.width / 2, self.height / 2,
            text=guess_text, fill="#2962FF",
            font=("微软雅黑", 16)
        )

        # 添加庆祝元素
        self.canvas.create_text(
            self.width / 2, self.height / 2 + 30,
            text="✨✨✨", font=("Arial", 24)
        )

        # 启用重置按钮
        self.reset_button.config(state=tk.NORMAL)

    def reset_race(self):
        """重置比赛状态"""
        # 清空画布上的文字
        self.canvas.delete("all")

        # 重置赛道和装饰
        self.draw_track()
        self.add_decorations()

        # 重置队伍位置
        for team, items in self.boats.items():
            self.boats[team] = []  # 清空旧船队

        self.init_boats()  # 重新初始化船队

        # 重置队伍速度
        for team, data in self.teams.items():
            data["speed"] = random.uniform(2.0, 2.5)
            data["position"] = 0

        # 重置比赛状态
        self.running = False
        self.winner = None

        # 启用开始按钮
        self.start_button.config(state=tk.NORMAL)

        # 启用竞猜按钮
        for widget in self.guess_frame.winfo_children():
            if isinstance(widget, tk.Radiobutton):
                widget.config(state=tk.NORMAL)

        # 禁用重置按钮
        self.reset_button.config(state=tk.DISABLED)

        # 清除选择
        self.selected_team.set("")


if __name__ == "__main__":
    root = tk.Tk()
    app = DragonBoatRaceApp(root)
    root.mainloop()